<template>
  <div
    v-if="show"
    class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50"
    @click.self="$emit('close')"
  >
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
      <!-- 模态框标题 -->
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-medium text-gray-900">
          {{ isEdit ? '编辑宠物信息' : '添加宠物' }}
        </h3>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600"
        >
          <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mb-4 bg-red-50 border border-red-200 rounded-md p-4">
        <div class="flex">
          <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">{{ $t('message.error.server') }}</h3>
            <p class="mt-1 text-sm text-red-700">{{ error }}</p>
          </div>
        </div>
      </div>

      <!-- 表单 -->
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- 宠物照片 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            {{ $t('post.labels.petPhoto') }}
          </label>
          <ImageUpload
            v-model="form.photo"
            :preview-url="previewUrl"
            accept="image/*"
            :max-size="5"
            @error="handleImageError"
          />
        </div>

        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 宠物名称 -->
          <div>
            <label for="name" class="block text-sm font-medium text-gray-700">
              宠物名称 <span class="text-red-500">*</span>
            </label>
            <input
              id="name"
              v-model="form.name"
              type="text"
              required
              class="mt-1 input-field"
              placeholder="请输入宠物名称"
            />
          </div>

          <!-- 物种 -->
          <div>
            <label for="species" class="block text-sm font-medium text-gray-700">
              物种 <span class="text-red-500">*</span>
            </label>
            <select
              id="species"
              v-model="form.species"
              required
              class="mt-1 input-field"
            >
              <option value="">请选择物种</option>
              <option
                v-for="species in petSpeciesOptions"
                :key="species.value"
                :value="species.value"
              >
                {{ species.label }}
              </option>
            </select>
          </div>

          <!-- 品种 -->
          <div>
            <label for="breed" class="block text-sm font-medium text-gray-700">
              品种
            </label>
            <input
              id="breed"
              v-model="form.breed"
              type="text"
              class="mt-1 input-field"
              placeholder="请输入品种（可选）"
            />
          </div>

          <!-- 颜色 -->
          <div>
            <label for="color" class="block text-sm font-medium text-gray-700">
              颜色 <span class="text-red-500">*</span>
            </label>
            <input
              id="color"
              v-model="form.color"
              type="text"
              required
              class="mt-1 input-field"
              :placeholder="$t('post.placeholders.enterColor')"
            />
          </div>

          <!-- 性别 -->
          <div>
            <label for="gender" class="block text-sm font-medium text-gray-700">
              性别 <span class="text-red-500">*</span>
            </label>
            <select
              id="gender"
              v-model="form.gender"
              required
              class="mt-1 input-field"
            >
              <option
                v-for="gender in petGenderOptions"
                :key="gender.value"
                :value="gender.value"
              >
                {{ gender.label }}
              </option>
            </select>
          </div>

          <!-- 年龄 -->
          <div>
            <label for="age" class="block text-sm font-medium text-gray-700">
              年龄
            </label>
            <input
              id="age"
              v-model.number="form.age"
              type="number"
              min="0"
              max="30"
              class="mt-1 input-field"
              placeholder="请输入年龄（可选）"
            />
          </div>
        </div>

        <!-- 描述 -->
        <div>
          <label for="description" class="block text-sm font-medium text-gray-700">
            描述
          </label>
          <textarea
            id="description"
            v-model="form.description"
            rows="3"
            class="mt-1 input-field"
            placeholder="请输入宠物的特征描述（可选）"
          ></textarea>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-end space-x-3 pt-6 border-t">
          <button
            type="button"
            @click="$emit('close')"
            class="btn-secondary"
            :disabled="loading"
          >
            取消
          </button>
          <button
            type="submit"
            class="btn-primary"
            :disabled="loading || !isFormValid"
          >
            <span v-if="loading" class="inline-flex items-center">
              <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              {{ isEdit ? '更新中...' : '添加中...' }}
            </span>
            <span v-else>
              {{ isEdit ? '更新宠物' : '添加宠物' }}
            </span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { petService } from '@/services/pets'
import { getFullImageUrl } from '@/utils/helpers'
import { usePetSpeciesOptions, usePetGenderOptions } from '@/utils/i18n-options'
import ImageUpload from '@/components/ImageUpload.vue'
import type { Pet, PetFormData } from '@/types'

// Props
interface Props {
  show: boolean
  pet?: Pet | null
}

const props = withDefaults(defineProps<Props>(), {
  pet: null
})

// Emits
const emit = defineEmits<{
  close: []
  success: [pet: Pet]
}>()
const { t } = useI18n()

// 状态
const loading = ref(false)
const error = ref('')

// 表单数据
const form = ref<PetFormData>({
  name: '',
  species: '',
  breed: '',
  color: '',
  gender: 'unknown',
  age: undefined,
  description: '',
  photo: null,
})

// 计算属性
const isEdit = computed(() => !!props.pet)

// 国际化选项
const petSpeciesOptions = computed(() => usePetSpeciesOptions())
const petGenderOptions = computed(() => usePetGenderOptions())
const previewUrl = computed(() => {
  if (props.pet?.photo_url) {
    return getFullImageUrl(props.pet.photo_url)
  }
  return null
})

const isFormValid = computed(() => {
  return form.value.name.trim() !== '' &&
         form.value.species !== '' &&
         form.value.color !== '' &&
         ['male', 'female', 'male_neutered', 'female_neutered', 'unknown'].includes(form.value.gender)
})

// 监听pet变化，初始化表单
watch(() => props.pet, (newPet) => {
  if (newPet) {
    form.value = {
      name: newPet.name || '',
      species: newPet.species || '',
      breed: newPet.breed || '',
      color: newPet.color || '',
      gender: newPet.gender || 'unknown',
      age: newPet.age || undefined,
      description: newPet.description || '',
      photo: null,
    }
  } else {
    // 重置表单
    form.value = {
      name: '',
      species: '',
      breed: '',
      color: '',
      gender: 'unknown',
      age: undefined,
      description: '',
      photo: null,
    }
  }
  error.value = ''
}, { immediate: true })

// 处理图片错误
const handleImageError = (errorMessage: string) => {
  error.value = errorMessage
}

// 提交表单
const handleSubmit = async () => {
  if (!isFormValid.value) return

  try {
    loading.value = true
    error.value = ''

    let response
    if (isEdit.value && props.pet) {
      response = await petService.update(props.pet.id, form.value)
    } else {
      response = await petService.create(form.value)
    }

    if (response.success && response.data) {
      emit('success', response.data)
    } else {
      throw new Error(response.message || t('message.error.server'))
    }
  } catch (err) {
    console.error('宠物操作失败:', err)
    error.value = err instanceof Error ? err.message : t('message.error.server')
  } finally {
    loading.value = false
  }
}
</script>
